package initc

import (
	"context"
	"kubem/config"
	"kubem/pkg/logger"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func initMetadata() {
	logger.Debug("init metadata namespace")
	// 1. 创建restconfig
	restconfig, err := clientcmd.BuildConfigFromFlags("", "metadata.kubeconfig")
	if err != nil {
		logger.Errorf("Error building kubeconfig: %s", err.Error())
		panic(err.Error())
	}
	// 2. 创建clientset
	clientset, err := kubernetes.NewForConfig(restconfig)
	if err != nil {
		logger.Errorf("Error building kubernetes clientset: %s", err.Error())
		panic(err.Error())
	}
	clusterVersion, err := clientset.DiscoveryClient.ServerVersion()
	if err != nil {
		logger.Errorf("Error getting cluster version: %s", err.Error())
	}
	logger.Infof("cluster version: [%s]", clusterVersion.String())
	// 检查元数据命名空间是否创建
	namespace, err := clientset.CoreV1().Namespaces().Get(context.TODO(), config.Conf.Metadata.Namespace, metav1.GetOptions{})
	if err != nil {
		// 不存在元数据命名空间
		logger.Infof("metadata namespace %s not exist, create it", config.Conf.Metadata.Namespace)
		var metadataNamespace corev1.Namespace
		metadataNamespace.Name = config.Conf.Metadata.Namespace
		_, err = clientset.CoreV1().Namespaces().Create(context.TODO(), &metadataNamespace, metav1.CreateOptions{})
		if err != nil {
			logger.Errorf("Error creating metadata namespace: %s", err.Error())
			panic(err.Error())
		}
		// 创建
		logger.Infof("metadata namespace %s created", config.Conf.Metadata.Namespace)
	} else {
		// 已经存在namespace
		logger.Infof("namespace %s exist", namespace.Name)
	}
}
